package com.ruoyi.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.client.PayClientPls;
import com.ruoyi.client.model.PayOrderCreateReqModel;
import com.ruoyi.client.request.PayOrderCreateRequest;
import com.ruoyi.client.response.PayOrderCreateResponse;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.pay.domain.MchApp;
import com.ruoyi.pay.mapper.MchAppMapper;
import com.ruoyi.pay.service.SysConfigService;
import com.ruoyi.pay.utils.DBApplicationConfig;
import com.ruoyi.pay.vo.PaymentRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;



@RestController
@RequestMapping("/api/paytest")
public class PaytestController extends BaseController {

    @Resource
    MchAppMapper mchAppMapper;

    @Autowired
    SysConfigService sysConfigService;

    @Autowired(required = false)
    protected HttpServletRequest request;   //自动注入request




    /** 调起下单接口 **/
    @PostMapping("/payOrders")
    public R doPay(@RequestBody PaymentRequest paymentRequest) {

        //参入支付参数
        String appId = paymentRequest.getAppId();
        Long amount = paymentRequest.getAmount();
        String mchOrderNo = paymentRequest.getMchOrderNo();
        String wayCode =    paymentRequest.getWayCode();
        String divisionMode = paymentRequest.getDivisionMode();
        String payDataType = paymentRequest.getPayDataType();
        String authCode = paymentRequest.getAuthCode();

        //查询商户信息
        MchApp mchApp = mchAppMapper.selectOne(MchApp.gw().eq(MchApp::getAppId, appId));
        if(mchApp == null || mchApp.getState() != 1 || !mchApp.getAppId().equals(appId)){
            throw new ServiceException("商户应用不存在或不可用");
        }

        //订单对象：   统一下单接口 apiUri = "api/pay/unifiedOrder";
        PayOrderCreateRequest request = new PayOrderCreateRequest();
        //阿里请求参数封装
        PayOrderCreateReqModel model = new PayOrderCreateReqModel();
        model.setMchNo(appId);
        model.setAppId(appId);
        model.setMchOrderNo(mchOrderNo);
        model.setWayCode(wayCode);
        model.setAmount(amount);
        // paypal通道使用USD类型货币
        model.setCurrency(wayCode.equalsIgnoreCase("pp_pc") ? "USD" :  "CNY");
        model.setClientIp(getClientIp());
        String username = LoginHelper.getLoginUser().getUsername();
        model.setSubject("[" + username + "商户联调]");
        model.setBody("[" + username + "商户联调]");

        //获取配置信息，用于设置地址
        DBApplicationConfig dbApplicationConfig = sysConfigService.getDBApplicationConfig();
        //回调地址
        model.setNotifyUrl(dbApplicationConfig.getMchSiteUrl() + "/api/anon/paytestNotify/payOrder");
        //分账模式
        model.setDivisionMode(Byte.valueOf(divisionMode));
        //设置扩展参数
        JSONObject extParams = new JSONObject();
        if(StringUtils.isNotEmpty(payDataType)) {
            extParams.put("payDataType", payDataType.trim());
        }
        if(StringUtils.isNotEmpty(authCode)) {
            extParams.put("authCode", authCode.trim());
        }
        model.setChannelExtra(extParams.toString());
        request.setBizModel(model);

        //创建客户端
         String paySiteUrl = dbApplicationConfig.getPaySiteUrl();
         String appSecret = mchApp.getAppSecret();
        PayClientPls payClient = new PayClientPls(paySiteUrl, appSecret );

        try {
            //下单请求： http://127.0.0.1:8080/api/pay/unifiedOrder，
            PayOrderCreateResponse response = payClient.execute(request);
            if(null == response){
                throw new ServiceException("下单接口调用无响应！");
            }
            if(response.getCode() != 0){
                throw new ServiceException(response.getMsg());
            }
            return R.ok(response.get());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    /** 获取客户端ip地址 **/
    public String getClientIp() {
        String ipAddress = null;
        ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }

        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }


}
